package top.pengdong.pictureShare.tweet.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.pengdong.pictureShare.common.model.R;
import top.pengdong.pictureShare.common.model.SysConstant;

import java.util.Date;
import java.util.Map;

/**
 * @description: 统计记录数据
 * @projectName: pictureShare
 * @see: top.pengdong.pictureShare.tweet.controller
 * @author: pc
 * @createTime: 2022/5/1 14:19
 * @version: 1.0
 */
@RestController
@RequestMapping("api/count")
public class CountViewController {


	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 进行网页访问统计 TODO 后期1添加ip记录访问
	 * @return
	 */
	@RequestMapping(value = "/get_view", method = RequestMethod.GET)
	public R getCountView() {
		if (redisTemplate.opsForHash().get(SysConstant.VIEW_COUNT, DateUtil.today()) == null ){
			redisTemplate.opsForHash().put(SysConstant.VIEW_COUNT,
					DateUtil.today() , 0);
		}
		Long count = redisTemplate.opsForHash().increment(SysConstant.VIEW_COUNT, DateUtil.today(), 1);
		return R.ok("用户历史访问量").put("result", count);
	}

	/**
	 * 进行网页历史访问统计 TODO 记录其实还可以进行改进，添加开时间和结束时间
	 * @return
	 */
	@RequestMapping(value = "/get_view_list", method = RequestMethod.GET)
	public R getCountViewList() {
		if (redisTemplate.opsForHash().keys(SysConstant.VIEW_COUNT) == null ){
			return R.error(500, "获取失败服务器问题");
		}

		return R.ok("用户访问量有").put("result",
				(Map<String, Integer>)redisTemplate.opsForHash().entries(SysConstant.VIEW_COUNT));
	}
}